from api.tools.token import AuthJWT
from api.models.user import UserModel
from django.http.request import HttpRequest
from django.http.response import JsonResponse
from django.utils.deprecation import MiddlewareMixin


class UserAuthMiddleware(MiddlewareMixin):
    ''' 用户权限的中间件，处理路由是否需要登陆 '''
    def dont_required_permission_path(self, path: str) -> bool:
        ''' 不需要权限的路径 '''
        path_list = ['/api/user/login/', '/api/user/register/']
        if path in path_list or path.startswith('/static'):
            return True
        if path.startswith('/api/user/upload'):
            return True
        return False

    def process_request(self, request: HttpRequest):
        # 对请求路径进行鉴权，判断是否需要权限才能访问
        path_auth_result = self.dont_required_permission_path(request.path)
        if not path_auth_result:
            # 获取token
            token = request.headers.get('token')
            token = token if token else request.headers.get('X-Token')
            # token校验
            data = AuthJWT.decode(token)
            if not data:
                return self.error_resp()
            # 将用户信息挂载到request对象上
            request.user = self.get_user(data)

    def error_resp(self, code: int=5000, message: str='没有权限，请登陆后重试!') -> JsonResponse:
        ''' 错误的响应数据 '''
        error_json = {'code': code, 'data': None, 'message': message}
        return JsonResponse(error_json)
    
    def get_user(self, data: dict) -> UserModel:
        ''' 获取用户模型对象 '''
        user_id = data.get('id')
        return UserModel.objects.get(pk=user_id)



